// pages/home/me.js
const api = require("../request/api")
const request = require("../request/request")
const util = require("../utils/util")
const App = getApp();
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({

    /**
     * 页面的初始数据
     */
    data: {
      content_money: '1000万',
        orderMenu: [{
            id: '0',
            title: '待付款',
            icon: '/images/icon_not_pay.png',
            num: 0,
            targetUrl: '/pages/order/list?index=1',
        },
        {
            id: '1',
            title: '待发货',
            icon: '/images/icon_not_deliver.png',
            num: 0,
            targetUrl: '/pages/order/list?index=2'
        },
        {
            id: '2',
            title: '待收货',
            icon: '/images/icon_not_receive.png',
            num: 0,
            targetUrl: '/pages/order/list?index=3'
        },
        {
            id: '3',
            title: '已完成',
            icon: '/images/icon_not_comment.png',
            num: 0,
            targetUrl: '/pages/order/list?index=4'
        },
        ],
        myinfo: {},
        uid: '',
        avatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
        nickName: '微信昵称',
        if_register: false,
        showButtonTab: true,
        openid: '',
        session_key: '',
        user_role: 0,
        eid: '',
        show: true,
        etype: '',
        more_list: [],
        eshop_id: '',
        accountInfo: '',
        showSaveButton: false,
        service_list: [
            {
                title: '商家中心',
                icon: '/images/个人中心图片/积分中心.png',
                num: 0,
                page_url: '/pages/shop/shop_center',
                id: 1,
            },
            {
                title: '分销中心',
                icon: '/images/个人中心图片/联系客服.png',
                num: 0,
                page_url: '/pages/distribution/distribution_center',
                id: 2,
            },
            {
                title: '优惠券列表',
                icon: '/images/个人中心图片/优惠券.png',
                num: 0,
                page_url: '/pages/ticket/newticket',
            },
            {
                title: '地址信息',
                icon: '/images/个人中心图片/地址信息.png',
                num: 0,
                page_url: '/pages/address/address',
            },

        ],
        property_list: [
            // {
            //     title: '我的余额',
            //     icon: '/images/个人中心图片/积分中心.png',
            //     num: 0,
            //     page_url: '/pages/balance/balance_center',
            // },
            // {
            //     title: '我的积分',
            //     icon: '/images/个人中心图片/联系客服.png',
            //     num: 0,
            //     page_url: '/pages/point/point_center',
            // },
        ]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.init_data(options)
        this.get_myinfo()
        this.get_open_id()
        this.get_more_list()
        // 获得popup组件
        this.popup = this.selectComponent("#popup");
        // this.getAccountInfoSync()
    },
    showPopup() {
      this.popup.showPopup();
    },
    // 取消事件
    _close() {
      console.log('你点击了关闭按钮');
      this.popup.hidePopup();
    },
    onChooseAvatar(e) {
        const { avatarUrl } = e.detail
        this.setData({
            avatarUrl,
            showSaveButton: true
        })
    },
    closeButtonTab() {
      this.setData({
        showButtonTab: false
    })
    },
    saveAvatar() {
      let that = this
      let url = this.data.avatarUrl;
      wx.uploadFile({
        url: 'https://api.gangjinhui.cn/ashop102/uploadfile', //你的上传接口地址
        filePath: url,
        name: 'imgFile', //必填，文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
        formData: {
          'user': '1' // 这里的user是自定义的字段，test是传入的值
        },
        success: function(uploadFileRes) {
          console.log(uploadFileRes.data)
          const  obj2 = JSON.parse(uploadFileRes.data)
          console.log(obj2)
          let params = {
              uid: that.data.uid,
              avatar: obj2.data.url,
              img: obj2.data.url
          }
          console.log(api.myavatarupdate)
          request.post(api.myavatarupdate, params).then(res => {
            console.log(res)
              if(res === true) {
                that.setData({
                  showSaveButton: false
              })
              util.showToast("修改头像成功！")
            } else {
              util.showToast("修改头像失败！")
            }
          })
        }
      })
    },
    receiveValueFromChild(event) {
      let nickName = event.detail.value
      this.setData({
        nickName
    })
      console.log(event.detail.value); // 输出：这是子组件的数据
    },
    init_data(options) {
        let uid = util.getAppValue(App.globalData.uid)
        console.log(App);
        let eshop_id = App.globalData.eshop_id
        let eid = App.globalData.eid
        let etype = App.globalData.etype

        if (!uid) {
            uid = 1
        }

        this.setData({
            if_register: App.globalData.if_register,
            uid,
            options,
            eid,
            eshop_id,
            etype,
        })
        let avatarUrl = App.globalData.avatarUrl
        let nickName = App.globalData.userInfo.nickName

        if (avatarUrl) {
            this.setData({
                avatarUrl,
                nickName,
            })
        }

        console.log(this.data);

    },

    get_more_list() {
        let params = {
            key: this.data.keyword_value,
            uid: this.data.uid
        }
        util.showLoading('加载中')
        request.post(api.goods_more, params).then(res => {
            util.hideLoading()
            this.setData({
                more_list: res
            })
        })
    },

    go_detail_from_component(e) {
        let id = e.detail.currentTarget.dataset.id
        if (!id) {
            id = 10
        }
        wx.navigateTo({
            url: '/pages/good/detail?id=' + id,
        })
    },

    cart_add() {
        util.showLoading("正在添加")
        let params = {
            // goods_num: this.data.cart_num,
            goods_id: this.data.goods_id,
            uid: this.data.uid
        }
        request.post(api.cart_add, params).then(res => {
            this.setData({
                if_show_box: false
            })
            util.showToast("已加入购物车")
        })
    },

    go_vip() {
        let url = '/pages/vip/vip'
        wx.navigateTo({
            url,
        })
    },

    check_register(e) {
        if (!this.data.if_register) {
            this.get_user_profile(e)
            return false
        }
        return true
    },

    get_myinfo() {
        let params = {
            uid: this.data.uid
        }
        request.post(api.myinfo, params).then(res => {
          App.globalData.avatarUrl  = res.avatar
          let avatarUrl = res.avatar
          let nickName = res.true_name
          console.log(res)
            this.setData({
                myinfo: res,
                avatarUrl,
                nickName
            })
        })
    },
    go_next_page(e) {
        let before_next_page = this.data.before_next_page
        if (before_next_page == 'order') {
            this.go_order()
        }
        if (before_next_page == 'manager') {
            this.go_manager()
        }
        if (before_next_page == 'order_another') {
            this.go_order_another(e)
        }
        if (before_next_page == 'expert') {
            this.go_expert()
        }
    },

    get_user_profile(e) {
        wx.getUserProfile({
            desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: res => {
                App.globalData.userInfo = res.userInfo
                App.globalData.if_register = true
                this.init_data(this.data.options)
                this.go_next_page(e)
                // let pages = getCurrentPages()
                // let prev_page = pages[pages.length - 2]
                // prev_page.onLoad()
                // util.goBack()
            },
            fail: res => {
            }
        })
    },

    get_open_id() {
        wx.login({
            success: res => {
                if (res.code) {
                    let post_data = {
                        sid: 0,
                        code: res.code
                    }
                    request.post(api.login, post_data).then(res => {
                        this.setData({
                            openid: res.openid,
                            session_key: res.session_key
                        })
                    })
                }
            },
            fail: res => {
                console.log(res);
            }
        })
    },

    go_login() {
        wx.navigateTo({
            url: '/pages/login/login',
        })
    },
    go_service(e) {
        let id = e.currentTarget.dataset.id
        if (id == 1) {
            if (this.data.eid == 0 && this.data.etype == 0 && this.data.eshop_id == 0) {
                this.go_expert_register()
                return
            }
            if (this.data.etype != 11) {
                util.showToast('只有店长才能进入')
                return
            }
        }

        if (id == 2) {
            if (this.data.eid == 0 && this.data.etype == 0 && this.data.eshop_id == 0) {
                this.go_expert_register()
                return
            }
            if (this.data.etype != 1 && this.data.uid != 1) {
                util.showToast('只有分销员才能进入')
                return
            }
        }

        var targetUrl = e.currentTarget.dataset.url;
        wx.navigateTo({
            url: targetUrl,
        });
    },

    go_expert_register() {
        wx.navigateTo({
            url: '/pages/shop/shop_register',
        })
    },

    go_order() {
        this.setData({
            before_next_page: 'order'
        })
        let if_register = this.check_register()
        if (!if_register) {
            return
        }
        wx.navigateTo({
            url: '/pages/order/list',
        })
    },

    go_order_another(e) {
        this.setData({
            before_next_page: 'order_another'
        })
        let if_register = this.check_register(e)
        if (!if_register) {
            return
        }
        let url = e.currentTarget.dataset.url
        wx.navigateTo({
            url,
        })
    },

    // getAccountInfoSync() {
    //     const accountInfo = wx.getAccountInfoSync().miniProgram.version
    //     this.setData({ accountInfo });
    // },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})